package com.example.Dao;

import com.example.pojo.Comment;
import com.example.utils.ConnUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
    public int getTotal(){
        int flag=0;
        Connection conn= ConnUtils.getConn();
        String sql="select count(*) from comment";
        try {
            PreparedStatement pst=conn.prepareStatement(sql);
            ResultSet rs= pst.executeQuery();
            if(rs.next()){
                flag=rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return flag;
    }
    //管理员角度
    public List<Comment> getALlComment(int currentPage, int pageSize){//查询多条数据，一定返回List;分页数据
        List<Comment> list=new ArrayList<>();
        Connection conn=ConnUtils.getConn();
        String sql="select * from comment limit ?,?";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            //执行
//            pst.setString(1,type);
            pst.setInt(1,(currentPage-1)*pageSize);
            pst.setInt(2,pageSize);
            java.sql.ResultSet rs= pst.executeQuery();
            //封装
            while(rs.next()){ //rs.next()----->News对象------>List
                Comment n=new Comment(rs.getInt(1),
                        rs.getInt(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getInt(5),
                        rs.getInt(6));
                //把n对象添加List集合中
                list.add(n);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return list;
    }
    //看评论
    public Comment getCommentInfo(int comId){
        Comment n=null;
        Connection conn=ConnUtils.getConn();
        String sql="select * from comment where comId=?";
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setInt(1,comId);
            ResultSet rs= pst.executeQuery();
            if(rs.next()){
                n=new Comment(rs.getInt(1),
                        rs.getInt(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getInt(5),
                        rs.getInt(6));
            }
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return n;
    }
    // 添加评论
    public int addComment(Comment comment) {
        int flag = 0;
        Connection conn = ConnUtils.getConn();
        // 移除 comId，让数据库自动生成（如果 comId 是自增主键）
        String sql = "insert into comment(userId, comContent, comTime, comLikes, newsId) values(?, ?, SYSDATE(), ?, ?)";

        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setInt(1, comment.getUserId());
            pst.setString(2, comment.getComContent());
            pst.setInt(3, comment.getComLikes()); // 注意：这里应该是 int 类型
            pst.setInt(4, comment.getNewsId());
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            ConnUtils.closeConnection(conn);
        }
        return flag;
    }
    //删除评论
    public int deleteCommentById(int comId){
        int flag=0;
        Connection conn=ConnUtils.getConn();
        String sql="delete from Comment where comId=?";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setInt(1, comId);
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return flag;
    }
    //批量删除
    public  int deleteBatchComment(List<Integer> ids){
        int flag=0;
        Connection conn=ConnUtils.getConn();
        //自动提交关闭(保持一致性----事务处理)
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        StringBuffer sbuffer=new StringBuffer();//可变长的字符串
        for(int i=0;i<ids.size();i++){
            sbuffer.append("?");  //0?,1?,2?
            if(i<ids.size()-1){
                sbuffer.append(",");
            }
        }
        String sql="delete from Comment where comId in ("+sbuffer.toString()+")";
        System.out.println(sql);
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            for(int i=0;i< ids.size();i++){
                pst.setInt(i+1,ids.get(i));
            }
            flag= pst.executeUpdate();
            if(flag>0){
                //手动提交
                conn.commit();
            }
        } catch (SQLException e) {
            //回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return flag;
    }
    //按新闻ID查询
    // 在CommentDao类中添加这个方法
    public List<Comment> getCommentsByNewsId(int newsId) {
        List<Comment> list = new ArrayList<>();
        Connection conn = ConnUtils.getConn();
        String sql = "select * from comment where newsId = ? order by comTime desc";
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setInt(1, newsId);
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                Comment comment = new Comment(
                        rs.getInt("comId"),
                        rs.getInt("userId"),
                        rs.getString("comContent"),
                        rs.getString("comTime"),
                        rs.getInt("comLikes"),
                        rs.getInt("newsId")
                );
                list.add(comment);
            }
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            ConnUtils.closeConnection(conn);
        }
        return list;
    }

        // 评论点赞
        public int incrementCommentLikes(int comId) {
            int flag = 0;
            Connection conn = ConnUtils.getConn();
            String sql = "UPDATE comment SET comLikes = COALESCE(comLikes, 0) + 1 WHERE comId = ?";

            try {
                PreparedStatement pst = conn.prepareStatement(sql);
                pst.setInt(1, comId);
                flag = pst.executeUpdate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                ConnUtils.closeConnection(conn);
            }
            return flag;
        }

        // 评论取消点赞
        public int decrementCommentLikes(int comId) {
            int flag = 0;
            Connection conn = ConnUtils.getConn();
            String sql = "UPDATE comment SET comLikes = GREATEST(COALESCE(comLikes, 0) - 1, 0) WHERE comId = ?";

            try {
                PreparedStatement pst = conn.prepareStatement(sql);
                pst.setInt(1, comId);
                flag = pst.executeUpdate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                ConnUtils.closeConnection(conn);
            }
            return flag;
        }

        // 获取评论点赞数
        public int getCommentLikes(int comId) {
            int likes = 0;
            Connection conn = ConnUtils.getConn();
            String sql = "SELECT comLikes FROM comment WHERE comId = ?";

            try {
                PreparedStatement pst = conn.prepareStatement(sql);
                pst.setInt(1, comId);
                ResultSet rs = pst.executeQuery();
                if (rs.next()) {
                    likes = rs.getInt("comLikes");
                }
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                ConnUtils.closeConnection(conn);
            }
            return likes;
        }


}
